import React, { useEffect, useState } from 'react';
import { useParams } from 'umi';
import { Card, Descriptions, Tag, Spin, message } from 'antd';
import { getSubmissionById } from '@/services/submission';
import type { Submission, ResultVOSubmission } from '@/types/openapi';

const ResultPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [submission, setSubmission] = useState<Submission | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchData = async () => {
    setLoading(true);
    try {
      const res: ResultVOSubmission = await getSubmissionById(id!);
      if (res.code === 200 && res.data) {
        setSubmission(res.data);
      } else {
        message.error(res.message || '找不到该提交');
      }
    } catch (e) {
      message.error('请求失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [id]);

  if (loading) return <Spin />;

  if (!submission) return null;

  return (
    <Card title={`提交结果 ID：${submission.submission_id}`}>
      <Descriptions bordered column={1}>
        <Descriptions.Item label="题目 ID">{submission.problem_id}</Descriptions.Item>
        <Descriptions.Item label="语言">{submission.language}</Descriptions.Item>
        <Descriptions.Item label="状态">
          <Tag color={submission.status === 'ACCEPTED' ? 'green' : 'red'}>
            {submission.status}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="耗时">{submission.timeUsed}</Descriptions.Item>
        <Descriptions.Item label="内存">{submission.memoryUsed}</Descriptions.Item>
        <Descriptions.Item label="输入">{submission.inputWrongAnswer}</Descriptions.Item>
        <Descriptions.Item label="预期输出">{submission.expected}</Descriptions.Item>
        <Descriptions.Item label="实际输出">{submission.stdout}</Descriptions.Item>
        <Descriptions.Item label="错误信息">{submission.error}</Descriptions.Item>
        <Descriptions.Item label="源代码">
          <pre style={{ whiteSpace: 'pre-wrap' }}>{submission.code}</pre>
        </Descriptions.Item>
      </Descriptions>
    </Card>
  );
};

export default ResultPage;
